package com.lepu.app.main.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragment;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UmengHelper;
import com.lepu.app.fun.my.MyLectureDetailActivity;
import com.lepu.app.fun.my.adapter.AdapterLecture;
import com.lepu.app.fun.my.bean.BeanLecture;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.pasm.R;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MainTabFragmentLecture extends BaseFragment implements AsyncRequest, SwipeRefreshLayout.OnRefreshListener {

    private static final String REQUEST_DATA = "request_data";

    private static final int MSG_DATA_SUCCESS = 10;
    private static final int MSG_DATA_FAIL = 11;

    private View mMainView = null;
    private boolean mInitDataSuccess = false;// 是否加载完数据

    public SwipeRefreshLayout mGoogleRefreshLayout = null;
    private ListView mDataListView = null;
    private AdapterLecture mDataAdapter = null;
    private ArrayList<BeanLecture> mDataArrayList = null;

    public boolean mRefreshFlag = true;

    @SuppressLint("InflateParams")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMainView = LayoutInflater.from(getActivity()).inflate(
                R.layout.main_tab_fragment_lecture, null, false);
        init();
    }

    @Override
    public void onResume() {
        super.onResume();

        UmengHelper.OnPageStart(UmengEvent.page_lecture);
    }

    @Override
    public void onPause() {
        super.onPause();

        UmengHelper.OnPageEnd(UmengEvent.page_lecture);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        ViewGroup p = (ViewGroup) mMainView.getParent();
        if (p != null) {
            p.removeAllViewsInLayout();
        }
        return mMainView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mInitDataSuccess = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
            if (!mInitDataSuccess || mRefreshFlag) {
                // 第一次进入页面获取数据
                mRefreshFlag = false;
                // 第一次进入页面获取数据

                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        mGoogleRefreshLayout.setRefreshing(true);  //直接调用是没有用的
                    }
                }, 100);
                request();
            }
        }
    }

    /*
     * 初始化ui控件，不要初始化数据！！！！
     *
     * 初始化控件，需要用mMainView.findViewById 不能使用findViewById，否则程序会闪退的
     */
    private void init() {
        //5.0以下关闭硬件加速
        Utils.setLayerTypeOff(mMainView);

        mDataListView = (ListView) mMainView.findViewById(R.id.dataListView);
        mDataListView.setOnItemClickListener(mOnItemClickListener);

        mGoogleRefreshLayout = (SwipeRefreshLayout) mMainView.findViewById(R.id.swipeLayout);
        mGoogleRefreshLayout.setOnRefreshListener(this);
        mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
                R.color.color_listview_refresh_2,
                R.color.color_listview_refresh_3,
                R.color.color_listview_refresh_4);
    }

    AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            BeanLecture item = mDataArrayList.get(position);

            //进入活动详情
            Intent intent = new Intent(getActivity(), MyLectureDetailActivity.class);
            intent.putExtra("LectureID", item.ActivityID);
            intent.putExtra("Cover", item.ImageUrl);
            MainTabActivity.getInstance().startActivity(intent, true);
        }
    };

    private void showHideNoDataLayout(boolean isShow) {
        LinearLayout noDataLayout = (LinearLayout) mMainView.findViewById(R.id.noDataLayout);
        if (noDataLayout != null) {
            if (isShow) {
                if (mDataArrayList == null || mDataArrayList.size() == 0) {
                    noDataLayout.setVisibility(View.VISIBLE);
                } else {
                    noDataLayout.setVisibility(View.GONE);
                }
            } else {
                noDataLayout.setVisibility(View.GONE);
            }
        }
    }

    public void request() {

        String url = Setting.getActivityListUrl();

        Map<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject();
        try {
            params.put("DeviceID", Setting.DEVICEID);
            params.put("ApplicationID", Setting.APPLICATIONID);

            params.put("UserID", LoginUtil.getUserId());
            params.put("LoginToken", LoginUtil.getLoginToken());

        } catch (Exception e) {
        }
        map.put("ht", params);

        ApiClient.http_post(url, map, null, this, REQUEST_DATA, true);
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_DATA_SUCCESS:

                    if (getActivity() == null) {
                        return;
                    }

                    ArrayList<BeanLecture> dataList = (ArrayList<BeanLecture>) msg.obj;
                    if (dataList != null && dataList.size() > 0) {

                        //mInitDataSuccess = true;
                        mDataArrayList = dataList;

                        showHideNoDataLayout(false);
                    } else {
//					UIHelper.showToast(MyApplication.getInstance(),
//							R.string.no_data);

                        if (mDataArrayList != null && mDataArrayList.size() > 0) {
                            mDataArrayList.clear();
                        }
                        showHideNoDataLayout(true);
                    }

                    if (mDataArrayList == null) {
                        mDataArrayList = new ArrayList<BeanLecture>();
                    }

                    ImageView tempImageView = new ImageView(getActivity());
                    mDataListView.addHeaderView(tempImageView);

                    mDataAdapter = new AdapterLecture(getActivity(),
                            mDataArrayList);
                    mDataListView.setAdapter(mDataAdapter);

                    mDataListView.removeHeaderView(tempImageView);

                    // 更新完后调用该方法结束刷新
                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
                        }
                    }, 100);


                    break;
                case MSG_DATA_FAIL:

                    if (getActivity() == null) {
                        return;
                    }

                    // 更新完后调用该方法结束刷新
                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            mGoogleRefreshLayout.setRefreshing(false);  //直接调用是没有用的
                        }
                    }, 100);

                    showHideNoDataLayout(true);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    @Override
    public void onRefresh() {
        request();
    }

    @Override
    public void RequestComplete(Object object, Object data) {
        if (object.equals(REQUEST_DATA)) {
            // 解析json data
            ArrayList<BeanLecture> dataArraylist = BeanLecture
                    .parseJsonData((String) data);

            ArrayList<BeanLecture> resultList = new ArrayList<BeanLecture>();
            if (dataArraylist != null && dataArraylist.size() > 0) {
                ArrayList<BeanLecture> ingList = new ArrayList<BeanLecture>();
                ArrayList<BeanLecture> readyList = new ArrayList<BeanLecture>();
                ArrayList<BeanLecture> edList = new ArrayList<BeanLecture>();

                for (BeanLecture item : dataArraylist) {
                    if (item.ActivityStatus.equals("2")) {
                        //正在进行
                        ingList.add(item);
                    } else if (item.ActivityStatus.equals("1")) {
                        //即将开始
                        readyList.add(item);
                    } else if (item.ActivityStatus.equals("3")) {
                        //已经结束
                        edList.add(item);
                    }
                }

                Collections.sort(ingList, new SortByStatus(true));
                Collections.sort(readyList, new SortByStatus(true));
                Collections.sort(edList, new SortByStatus(false));

                resultList.addAll(ingList);
                resultList.addAll(readyList);
                resultList.addAll(edList);
            }

            Message msg = mHandler.obtainMessage();
            msg.what = MSG_DATA_SUCCESS;
            msg.obj = resultList;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    public void RequestError(Object object, int errorId, String errorMessage) {
        if (object.equals(REQUEST_DATA)) {
            mHandler.sendEmptyMessage(MSG_DATA_FAIL);
        }
    }

    class SortByStatus implements Comparator {

        private boolean isAsc;

        public SortByStatus(boolean asc) {
            isAsc = asc;
        }

        public int compare(Object o1, Object o2) {
            BeanLecture s1 = (BeanLecture) o1;
            BeanLecture s2 = (BeanLecture) o2;

            Date d1 = DateUtilBase.dateFromString(s1.StartTime, DateUtilBase.DATE_ALL_ALL);
            Date d2 = DateUtilBase.dateFromString(s2.StartTime, DateUtilBase.DATE_ALL_ALL);

            long t1 = d1.getTime();
            long t2 = d2.getTime();
            if (isAsc) {
                if (t2 > t1) {
                    return -1;
                } else if (t1 == t2) {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                if (t2 < t1) {
                    return -1;
                } else if (t1 == t2) {
                    return 0;
                } else {
                    return 1;
                }
            }
        }
    }
}
